//index.js
const myAudio = wx.getBackgroundAudioManager()
import api from '../../utils/api.js'
import util from '../../utils/util.js'
//获取应用实例
const app = getApp()
var shareData = {}
var pid = ''
var tid = ''
var mid = ''
Page({
  data: {
    haveAd:false, 
    isIndex:true,
    gifHeight:'0',
    isMusic:false,
    music:{},
    unitid:'',
    albumData:{},
    imgs:[],
    // 用于版本控制是否开启选择照片功能
    show:true,
  },
  onLoad: function (options) {
    let that = this
    pid = options.pid // 相册id
    tid = options.tid // 只保存了用户上传图片内容id
    mid = options.mid // 模板id
    wx.showLoading({
      title: '加载中',
    })
    getApp().setWatcher(this.data, this.watch); // 设置监听器
    this.getHomeData(pid)
  },
  onShow: function () {
    // 判断播放状态
    if (app.globalData.isMusic == true){
      this.setData({ isMusic:false})
    }
    this.audioPlay()
    // 获取分享数据
    shareData = util.getShareData()
    this.getAd()
    // 防止从making页面中返回到首页音乐不变
    if (app.globalData.changeMusic == 1){
      app.createMusic(this.data.music)
      app.globalData.changeMusic = 0
    }
  },
  // 监听music数据的改变创建音频
  watch: {
    music: function (newValue) {
      app.createMusic(newValue)
    },
    albumData: function (newValue) {
      // 无pid无tid无mid return
      if (!pid && !tid && !mid) return
      // 记录播放的id
      const visitTimes = wx.getStorageSync('visitTimes')
      if (visitTimes) {
        if (visitTimes[newValue.mid]) {
          const times = visitTimes[newValue.mid]
          visitTimes[newValue.mid] = parseInt(times) + 1
          wx.setStorageSync('visitTimes', visitTimes)
        } else {
          visitTimes[newValue.mid] = 1
          wx.setStorageSync('visitTimes', visitTimes)
        }
      } else {
        let data = {}
        data[newValue.mid] = 1
        wx.setStorageSync('visitTimes', data)
      }
      // 上报微信
      util.visitCount(newValue.mid, newValue.title)
    }
  },
  // 获取广告
  getAd(){
    let that = this
    const data = wx.getStorageSync('advertise')
    if (data) {
      const advertise = data.advertise
      if (advertise[0]) {
        const adData = advertise[0]
        if (adData.is_show == 'true' && adData.unitid) {
          if (adData.unitid == '') {return}
          that.setData({
            haveAd: true,
            unitid: adData.unitid
          })
          // 当检查到globalData中的gifHeight有值，则先赋值给gifHeight，防止adYesFn()没有监听到
          if (app.globalData.gifHeight != 0){
            this.setData({
              gifHeight: app.globalData.gifHeight,
            })
          }
        }
      }
    }
  },
  // 监听广告获取失败，调整gif高度
  adNoFn(){
    this.setData({
      gifHeight:'0',
      haveAd: false,
    })
  },
  // 监听广告获取成功，调整gif高度
  adYesFn(){
    let that = this
    const windowWidth = wx.getSystemInfoSync().windowWidth
    let query = wx.createSelectorQuery();
    //选择id
    query.select('.adCom').boundingClientRect(function (rect) {
      let height = rect.height
      let gifHeight = parseInt(height * (750 / windowWidth))
      that.setData({
        gifHeight: `${gifHeight}rpx`,
      })
      app.globalData.gifHeight = `${gifHeight}rpx`
    }).exec();
  },
  // 获取首页数据
  getHomeData(pid){
    let data = { m: 'Home' }
    if (pid) { 
      data.pid = pid 
    }else{
      if (tid) { data.tid = tid }
      if (mid) { data.mid = mid }
    }
    api.getData(data).then(res=>{
      if(res.data.code == 1){
        let homeData = res.data.data.default
        this.setData({ show: res.data.data.show})
        // 当pid存在并有pidData
        if (pid && res.data.data.pidData){        
          //当pidData等于false，提示数据被删除并返回显示默认
          if (res.data.data.pidData == false){    
            wx.showToast({
              title: '抱歉，该相册已被删除！',
              icon: 'none',
              duration: 2000
            })
            return
          }
          // pidData为有效内容显示出pid内容
          homeData = res.data.data.pidData
        }
        // 当mid和tid存在
        if (tid && mid && res.data.data.tmidData) {
          //当tmidData等于false，提示数据被删除并返回显示默认
          if (res.data.data.tmidData == false) {
            wx.showToast({
              title: '抱歉，该相册已被删除！',
              icon: 'none',
              duration: 2000
            })
            return
          }
          // tmidData为有效内容显示出pid内容
          homeData = res.data.data.tmidData
        }
        if (homeData){
          if (homeData.audio) {
            this.setData({
              isMusic: true,
              music: {
                audio: homeData.audio,
                title: homeData.title,
                cover: homeData.cover
              },
            })
          }
          this.setData({
            albumData: {
              audio: homeData.audio,
              title: homeData.title,
              mid: homeData.mid,
              id: homeData.mid,  // 用于making页面
              bg: homeData.bg,
              cover: homeData.cover,
              gif1: homeData.gif1,
              gif2: homeData.gif2,
            },
            imgs: homeData.urls,
          })
          app.globalData.shareAlbumData = this.data.albumData
        }
        wx.hideLoading()
      }else{
        wx.hideLoading()
        wx.showToast({
          title: '抱歉，数据请求错误',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 上传图片
  chooseImg(){
    const that = this
    wx.chooseImage({
      sizeType: ['compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const tempFilePaths = res.tempFilePaths
        let imgs = []
        for (let i = 0; i<tempFilePaths.length;i++){
          const base64 = wx.getFileSystemManager().readFileSync(res.tempFilePaths[i], 'base64') 
          imgs.push(base64)
        }
        wx.showLoading({
          title: `制作中`
        })
        const data = { imgs }
        api.pushImgs(data).then(res => {
          if (res.statusCode == 413){
            wx.hideLoading()
            wx.showToast({
              title: '图片过大！请重新选择图片！',
              icon: 'none',
              duration: 2000
            })
            return
          }
          if (res.data.code == 1) {
            let imgs = []
            const data = res.data.data.urls
            // tid注释：保存了用户上传的图片id，在分享的时候加上模板id一起给后端，分享带tid，再显示出相应内容，这样做是为了保证进入页面为点击保存的时候就可以直接分享出去带有照片的内容
            const tid = res.data.data.tid
            if (data.length == 0) {
              wx.hideLoading()
              return
            }
            for (let i = 0; i < data.length; i++) {
              if(data[i].code == 0){
                imgs.push(data[i].url)
              }
            }
            app.globalData.makingImgs = imgs
            let url = ''
            url = `/pages/making/making?tid=${tid}`
            wx.navigateTo({ url })
            wx.hideLoading()
          }
        }).catch(() => {
          wx.hideLoading()
        })
      }
    })
  },
  // 收集fromid
  formSubmit(e){
    // 获取formid
    const formid = e.detail.formId;
    // 获取当前的日期(日)
    const formTime = new Date().getDate()
    // 检查formid日期
    const date = wx.getStorageSync('formTime')
    if (date && formTime == date) { return }
    const data = {
      m: 'formId',
      formid,
    }
    api.getData(data).then(res => {
      if (res.data.code == 1) {
        // 收集成功存储当前的日期(日)
        console.log('formid收集成功')
        wx.setStorageSync('formTime', formTime)
      }
    })
  },
  // 暂停背景音乐
  audioPause(){
    myAudio.pause()
    this.setData({
      isMusic: false
    })
  },
  // 播放背景音乐
  audioPlay() {
    myAudio.play()
    this.setData({
      isMusic: true
    })
  },
  // 分享统计
  countShare(){
    // 无pid return
    if(!pid) {
      util.shareIndexCount(this.data.albumData.mid, this.data.albumData.title)
      return
    }
    // 上报微信
    util.shareCount(this.data.albumData.mid, this.data.albumData.title)
    // 上报后端
    const id = this.data.albumData.mid
    const data = {
      m:'shareTimes',
      id,
    }
    api.getData(data).then(res=>{
      if(res.data.code == 1){
        console.log('统计分享成功！')
      }
    })
  },
  onShareAppMessage: function () {
    this.countShare()
    // 分享分为三种情况：1、没有带有值分享默认首页；2、有pid分享带pid；3、有tid和mid分享带tid和mid
    let path = pid ? `pages/index/index?pid=${pid}` : `pages/index/index`
    if (!pid && tid && mid) {
      path = `pages/index/index?tid=${tid}&mid=${mid}`
    }
    return {
      title: shareData.title,
      imageUrl: shareData.imageUrl,
      path
    }
  }
})
